/**
 * Copyright (C) 2011 Andrew C. Love (DNC) <dnc.app.sup@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.dnc.cloak.framework.persistence;

import java.sql.Connection;
import java.sql.Driver;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

import com.dnc.cloak.framework.util.ClassUtil;

public class JDBCConnectionFactory {
    private static final String USERID = "user";
    private static final String PASSWORD = "password";

    static public Connection createConnection(String strDriver, String url, Properties properties, String userid, String password) throws Exception {
        Driver driver = (Driver)ClassUtil.forName(strDriver).newInstance();
        Properties connectionProperties  = (properties == null) ? new Properties() : properties;
        if (userid != null && userid.trim().length() != 0){
            connectionProperties.put(USERID, userid);
            connectionProperties.put(PASSWORD, password);
        }
        Connection connection = driver.connect(url, connectionProperties);
        connection.setAutoCommit(false);
        return connection;
	}

	static public Connection createConnection(String dataSourceName , String userName, String password) throws Exception {
		Properties properties = new Properties();
		properties.put(Context.INITIAL_CONTEXT_FACTORY, "com.dnc");

        Context initialContext = new InitialContext(properties);
        try {
            DataSource dataSource = (DataSource)initialContext.lookup(dataSourceName);
            Connection connection = dataSource.getConnection();
            connection.setAutoCommit(false);
            return connection;
        }
        finally {
            try {
                initialContext.close();
            }
            catch (Throwable ex) {
                ex.printStackTrace();
            }
        }
	}
}
